var CanvasImg = {
    imagelist: [],
    canvasGoodsImg: function(bgurl, itemtypeimg, codeimg, iteminfo, issave = true, callback) {
        api.showProgress({
            title: '',
            text: '合成图片',
            modal: false
        });
        var canvas = document.getElementById('sharecanvas');
        var ctx = canvas.getContext('2d');
        ctx.fillStyle = "#fff";
        canvas.width = 640;
        canvas.height = 1221;
        var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
        for (var i = 0; i < imageData.data.length; i += 4) {
            // 当该像素是透明的，则设置成白色
            if (imageData.data[i + 3] == 0) {
                imageData.data[i] = 255;
                imageData.data[i + 1] = 255;
                imageData.data[i + 2] = 255;
                imageData.data[i + 3] = 255;
            }
        }
        ctx.putImageData(imageData, 0, 0);
        var bj_img = new Image();
        bj_img.setAttribute('crossOrigin', 'anonymous');
        bj_img.src = bgurl;
        bj_img.onload = function() {
            ctx.drawImage(bj_img, 0, 0, canvas.width, canvas.height);
            var item_img = new Image();
            item_img.setAttribute('crossOrigin', 'anonymous');
            item_img.src = iteminfo.itempic;
            item_img.onload = function() {
                ctx.drawImage(item_img, 42, 60, canvas.width - 85, canvas.width - 50);
                //二维码地址
                var code_img = new Image();
                code_img.setAttribute('crossOrigin', 'anonymous');
                code_img.src = codeimg;
                code_img.onload = function() {
                    ctx.drawImage(code_img, canvas.width - 225, canvas.height - 260, 175, 175);
                    console.log('二维码地址:' + code_img.src);
                    /*商品的图标*/
                    var shoptype = "B";
                    var tb_img = new Image();
                    tb_img.setAttribute('crossOrigin', 'anonymous');
                    tb_img.src = itemtypeimg;
                    tb_img.onload = function() {
                        ctx.drawImage(tb_img, canvas.width - 590, canvas.width + 20, 35, 35);
                        //商品标题
                        var str = iteminfo.itemtitle;
                        ctx.fillStyle = '#605761';
                        ctx.lineWidth = 1;
                        ctx.textAlign = 'left';
                        ctx.textBaseline = "top";
                        ctx.font = '26px 微软雅黑';
                        var lineWidth = 0;
                        var canvasWidth = canvas.width - 60; //计算canvas的宽度
                        var initHeight = canvas.width + 19; //绘制字体距离canvas顶部初始的高度
                        var lastSubStrIndex = 0; //每次开始截取的字符串的索引
                        var curr_hang = 0
                        for (var i = 0; i <= str.length; i++) {
                            lineWidth += ctx.measureText(str[i]).width;
                            if (lineWidth > canvasWidth - 120) {
                                curr_hang++;
                                ctx.fillText(str.substring(lastSubStrIndex, i), 100, initHeight); //绘制截取部分
                                initHeight += 40; //字体的高度
                                lineWidth = 0;
                                lastSubStrIndex = i;
                            }
                            if (i == str.length - 1) {
                                curr_hang++;
                                ctx.fillText(str.substring(lastSubStrIndex, i + 1), 100, initHeight);
                            }
                        }
                        initHeight = canvas.width + 60;
                        /*销量*/
                        if (iteminfo.source_type == 'pdd') {
                            //拼多多自带万
                            var price = iteminfo.itemsale;
                        } else {
                            var price = changeW(iteminfo.itemsale);
                        }
                        ctx.fillStyle = '#aba0ac';
                        ctx.textAlign = 'left';
                        ctx.font = '22px 微软雅黑';
                        ctx.textBaseline = "top";
                        ctx.fillText(price, 120, initHeight + 93);

                        /*卷后价格*/
                        var price = 0;
                        var y = String(iteminfo.itemendprice).indexOf(".") + 1;
                        if (y <= 0) {
                            price = "¥ " + iteminfo.itemendprice + ".0";
                        } else {
                            price = "¥ " + iteminfo.itemendprice;
                        }

                        ctx.fillStyle = 'red';
                        ctx.textAlign = 'left';
                        ctx.font = '45px Helvetica';
                        ctx.textBaseline = "top";
                        ctx.fillText(price, 400, initHeight + 138);

                        /*原价格*/
                        var price = "¥ " + iteminfo.itemprice;
                        ctx.fillStyle = '#aba0ac';
                        ctx.textAlign = 'left';
                        ctx.font = '20px Helvetica';
                        ctx.textBaseline = "top";
                        ctx.fillText(price, 500, initHeight + 93);
                        /*删除线*/
                        ctx.strokeStyle = '#aba0ac';
                        ctx.lineWidth = 1; // 改变线的粗细
                        ctx.moveTo(561, initHeight + 102); // 起始点
                        ctx.lineTo(500, initHeight + 102); // 第二点(如果是一条直线的话，就是终点)
                        ctx.stroke();
                        /*秘券金额*/
                        var end_price = "¥ " + iteminfo.couponmoney;
                        ctx.fillStyle = '#FFF';
                        ctx.textAlign = 'left';
                        ctx.font = '25px Helvetica';
                        ctx.textBaseline = "top";
                        ctx.fillText(end_price, 135, initHeight + 147);
                        /*保存为图片*/
                        var imagedata = canvas.toDataURL("image/png");
                        var imgpic = imagedata;
                        console.log("合成成功:" + imagedata);
                        if (!issave) {
                            callback(0, imagedata);
                            return;
                        }
                        //保存图片
                        var trans = api.require('trans');
                        imagedata = imagedata.replace('data:image/png;base64,', '')
                        trans.saveImage({
                            base64Str: imagedata,
                            album: true,
                            imgPath: "fs://yqlm/",
                            imgName: iteminfo.itemid + "_yqlm.png",
                        }, function(ret, err) {
                            if (ret.status) {
                                console.log("保存合成图:" + JSON.stringify(ret));
                                callback(imgpic, "fs://yqlm/" + iteminfo.itemid + "_yqlm.png");
                            } else {
                                callback(1, "fs://yqlm/" + iteminfo.itemid + "_yqlm.png");
                            }
                        });
                        api.hideProgress();

                    }

                }

            }

        }

    },


    //分享图的合成
    canvasShareImg: function(info, codeimg, yqm, callback) {
        var canvas = document.getElementById('sharecanvas');
        var ctx = canvas.getContext('2d');
        ctx.fillStyle = "#fff";
        canvas.width = 1080;
        canvas.height = 1920;
        var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
        ctx.putImageData(imageData, 0, 0);
        //图片背景图
        var bj_img = new Image();
        bj_img.setAttribute('crossOrigin', 'anonymous');
        bj_img.src = info.url;
        bj_img.onload = function() {
            ctx.drawImage(bj_img, 0, 0, canvas.width, canvas.height);
            //二维码地址
            var code_img = new Image();
            code_img.setAttribute('crossOrigin', 'anonymous');
            code_img.src = codeimg;
            code_img.onload = function() {
              ctx.drawImage(code_img, canvas.width/2-150, canvas.height-500, 300, 300);
              var logoimg=new Image();
              logoimg.setAttribute('crossOrigin', 'anonymous');
              logoimg.src=info.logoimg;
              console.log(logoimg.src);
              logoimg.onload=function(){
                ctx.drawImage(logoimg, canvas.width/2-150, 50, 300, 300);
                //邀请码文字
                var yamstr = "邀请码:" + yqm;
                ctx.textAlign = 'left';
                ctx.font = 'bold 60px normal';
                ctx.fillStyle = '#5f41f8';
                ctx.fillText(yamstr, canvas.width/2-150, canvas.height-130, 300, 300);
                /*保存为图片*/
                var image = new Image();
                image.setAttribute('crossOrigin', 'anonymous');
                var imagedata = canvas.toDataURL("image/png");
                var imagedata2 = imagedata.replace('data:image/png;base64,', '')
                var trans = api.require('trans');
                var filename = "yqlm_" + info.itemid + "_shareimg.png";
                console.log("filename:" + filename);
                trans.saveImage({
                    base64Str: imagedata2,
                    imgPath: "fs://yqlm/",
                    imgName: filename,
                    album: true,
                }, function(ret, err) {
                    if (ret.status) {
                        var imgpah = "fs://yqlm/" + filename;
                        callback(imgpah);
                        console.log("分享图路径fs:" + imgpah);

                    }
                });
              }
            }
        }
    },

    //生成二维码
    makeQrcode: function(param, cb) {
        var FNScanner = api.require('FNScanner');
        FNScanner.encodeImg({
            content: param.text,
            saveToAlbum: false,
            saveImg: {
                path: 'fs://yqlm/erweima_'+param.itemid+'.png',
                w: 300,
                h: 300
            }
        }, function(ret, err) {
            if (ret.status) {
                console.log(JSON.stringify(ret));
                typeof cb=='function'&&cb(ret.imgPath);
            } else {
                console.log(JSON.stringify(err));
            }
        });
    },

    //打开图片浏览器
    //imagelist:图片数组
    //index:显示的索引
        openBrowserImg: function(imagelist, index) {
        var photoBrowser = api.require('photoBrowser');
        photoBrowser.open({
            images: imagelist,
            placeholderImg: 'widget://image/load-img.png',
            bgColor: '#000',
            activeIndex: index
        }, function(ret, err) {
            if (ret.eventType == 'click') {
                photoBrowser.close();
                api.closeFrame({
                    name: 'frame_photo'
                });

            }
            if (ret.eventType == 'change') {
                api.sendEvent({
                    name: 'photo_currindex',
                    extra: {
                        index: ret.index,
                        currurl: imagelist[ret.index]
                    }
                });
            }
            if (ret.eventType == 'longPress') {
                //长按图片提示
            }
            if (ret.eventType == 'show') {
                api.openFrame({
                    name: 'frame_photo',
                    url: 'widget://html/pyq_imgphoto.html',
                    bgColor: 'rgba(51,51,51,0)',
                    rect: {
                        x: 0,
                        y: api.winHeight - 50,
                        w: 'auto',
                        h: '50'
                    },
                    pageParam: {
                        currindex: index,
                        sunnum: imagelist.length,
                        currurl: imagelist[index],
                    }
                });

            }
        });
        //打开图片的 frame
    },

}
